package com.wxw.BaseLibrary.net;

import android.net.TrafficStats;

/**
 * @author david
 * @date 2020-05-18
 */
public class NetSpeed {
    private static final String TAG = NetSpeed.class.getSimpleName();
    private long lastTotalRxBytes = 0L;
    private long lastTimeStamp = 0L;
    private static final int K_B = 1024;

    public String getNetSpeed(int uid) {
        try {
            long nowTotalRxBytes = getTotalRxBytes(uid);
            long nowTimeStamp = System.currentTimeMillis();
            long ts = nowTimeStamp - lastTimeStamp;
            long speed = 0;
            if (ts > 0) {
                speed = ((nowTotalRxBytes - lastTotalRxBytes) * 1000 / ts);
            }
            lastTimeStamp = nowTimeStamp;
            lastTotalRxBytes = nowTotalRxBytes;
            String s = "";
            if (speed > K_B) {
                speed = speed / K_B;
                s = speed + " KB/s";
            } else {
                s = speed + " b/s";
            }
            return s;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "0 b/s";
    }

    public long getTotalRxBytes(int uid) {
        return TrafficStats.getUidRxBytes(uid) == TrafficStats.UNSUPPORTED ? 0 : (TrafficStats.getTotalRxBytes());
    }
}
